package com.im.partchat.mvp.persenter;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.im.partchat.base.IBaseView;
import com.im.partchat.bean.reponsed.BaseResponse;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * Created by fzl on 2017/6/28 0028.
 * VersionCode: 1
 * Desc:
 */

public class BasePresenter {

    protected  <T> Observable<T> responseCompose(Observable<BaseResponse<T>> observable, final IBaseView<T> baseView, @NonNull final String error) {

        return observable.map(new Function<BaseResponse<T>, T>() {
            @Override
            public T apply(BaseResponse<T> t) throws Exception {
                if (t.getCode().equals("1")) {
                    return t.getData();
                } else {
                    String msg = t.getMsg();
                    if (TextUtils.isEmpty(msg)) {
                        msg = error;
                    }
                    baseView.showError(msg);

                }
                return (T) new String("");
            }
        });
    }

    protected String NetErrorObservable( Throwable throwable){
        if (throwable instanceof ConnectException || throwable.getCause() instanceof ConnectException) {
            return "无法连接服务器或服务器异常";
        } else if (throwable instanceof TimeoutException ||
                throwable.getCause() instanceof TimeoutException ||
                throwable.getCause() instanceof SocketTimeoutException ||
                throwable instanceof SocketTimeoutException) {
            return "网络连接超时";

        } else {
            return throwable.getMessage();
        }
    }
}
